package com.juyu.miliao.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.primitives.Longs;
import com.juyu.miliao.api.config.IdCreater;
import com.juyu.miliao.api.constant.UserLineStatusConstant;
import com.juyu.miliao.api.dao.elasticsearch.FindDynamicElasticsearch;
import com.juyu.miliao.api.dao.mysql.*;
import com.juyu.miliao.api.dao.redis.*;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.domain.dto.GameAllRankingListDTO;
import com.juyu.miliao.api.domain.dto.GameAllRankingListLogDTO;
import com.juyu.miliao.api.domain.vo.FindDynamicVO;
import com.juyu.miliao.api.handler.IntegralRewardsAndPunishmentsHandler;
import com.juyu.miliao.api.rabbitMQ.HostRecentDevelopmentsMQ;
import com.juyu.miliao.api.service.*;
import com.juyu.miliao.api.service.Activity.SanGuoGameActivityService;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.api.util.RedisKeys;
import com.juyu.miliao.common.constant.*;
import com.juyu.miliao.common.domain.BillDetailBeans;
import com.juyu.miliao.common.domain.ConfigSms;
import com.juyu.miliao.common.domain.dto.HostRecentDevelopmentsDTO;
import com.juyu.miliao.common.util.SumAgeUtil;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.OpenApiStatus;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.LocalDate;
import java.util.*;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;


/**
 * wbf
 */
@Slf4j
@RestController
public class TestController {
    private final String EVERYDAY_MESSAGE = "平台近期接到多位用户举报，某些非认证主播利用平台私聊功能，"
            + "引导用户添加私人微信、QQ等第三方社交帐号，并索要红包、拉黑用户、骗取他人钱财。"
            + "请用户注意提防，于平台内沟通交流，避免被骗与财产损失。"
            + "若发现上述情况，请及时联系官方客服举报，感谢您的参与。";

    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private MatchHostService matchHostService;
    @Resource
    private HomeVideoDao homeVideoDao;
    @Resource
    private LineTimeRedisDao lineTimeRedisDao;
    @Resource
    private UserCallRedisDao userCallRedisDao;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AmqpTemplate rabbitTemplate;
    @Resource
    private IdCreater idCreater;
    @Resource
    private UserCoverUrlDao userCoverUrlDao;

    @Resource
    private OpenApiStatusDao openApiStatusDao;

    @Resource
    private UserVipDao userVipDao;

    @Resource
    private TalkingSkillService talkingSkillService;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;
    @Resource
    private SmsSenderRedisDao smsSenderRedisDao;
    @Resource
    private LineTimeService lineTimeService;
    @Resource
    private UserRedisDao userRedisDao;
    @Resource
    private ConfigSmsDao configSmsDao;

    @Autowired
    private UserCountDao userCountDao;

    @Autowired
    private FollowRedisDao followRedisDao;
    @Autowired
    private UserWalletDao userWalletDao;
    @Autowired
    private GameAllRankingListDao gameAllRankingListDao;
    @Autowired
    private GameAllRankingListLogDao gameAllRankingListLogDao;
    @Autowired
    private BillDetailDao billDetailBeansDao;

    @Autowired
    private CoolSummerActivitiesService coolSummerActivitiesService;

    @Autowired
    private IntegralRewardsAndPunishmentsHandler integralRewardsAndPunishmentsHandler;

    @Autowired
    private FindByIndexNameSessionRepository<? extends Session> sessionRepository;
    @Autowired
    private RedisOperationsSessionRepository redisOperationsSessionRepository;
    @Resource
    private SanGuoGameActivityService sanGuoGameActivityService;

    @Autowired
    private AppKeyService appKeyService;

    @Autowired
    private HostRecentDevelopmentsRedisDao hostRecentDevelopmentsRedisDao;

    @Autowired
    private FindDynamicElasticsearch findDynamicElasticsearch;

    @Autowired
    private UserVideoDao userVideoDao;

    @Autowired
    private PrivatePhotoDao privatePhotoDao;

    @Autowired
    private HostRecentDevelopmentsMQ hostRecentDevelopmentsMQ;
    @Resource
    private ObjectMapper objectMapper;

    @GetMapping("/testNetEase/sendSystemMessageByHostSort/{userId}")
    public Object sendSystemMessageByHostSort(@PathVariable("userId") String userId){
        String type = SpendSystemMessageType.SEND_SYSTEM_MESSAGE_BY_HOST_SORT.getCode();
        String message = "今日钻石榜榜单，加油宝贝\n第一名：%s\n第二名：%s\n第三名：%s\n第四名：%s\n第5名：%s\n";
        String[] args = {"八十万禁片总教头", "污到你湿\uD83D\uDE3B", "徐东东", "狂野夜晚", "禾厶 谷欠"};
        String[] colorsArgs = {"#fd67c9","#fd67c9","#fd67c9","#fd67c9","#fd67c9"};
        String formatStr=  String.format(message,args);
        Appkey appkey = appKeyService.getAppKeyByKey("rankingList");
        Map<String,Object> ext = new HashMap<>(1);
        ext.put("template",message);
        ext.put("templateValue",args);
        ext.put("templateColors",colorsArgs);
        ext.put("redirectUrl",appkey.getValue());
        return getSendMsg(Long.parseLong(userId),formatStr,type,ext);
    }
    public String getSendMsg(long userId ,String message,String type,Map<String,Object> ext) {
        String createLogInfo = "";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("title", "寻寻");
            map.put("type", type);
            map.put("message", message);
            map.put("ext",ext);
            createLogInfo= NetEaseCloudUserService.getSystemMessage(objectMapper.writeValueAsString(map), userId);
        } catch (Exception e) {
            e.getMessage();
        }
        return createLogInfo;
    }

//    @GetMapping("/testNetEase/del/session")
//    public Object delSession() {
//        Set<Object> set = stringRedisTemplate.opsForHash().keys(RedisKeys.HASH_COUNTLINE.getValue());
//        log.info("set::" + set);
//        if (set.size() <= 0) {
//            return set.size();
//        }
//        List<String> errorId = new ArrayList<>();
//        set.forEach(i -> {
//            try {
//                Map<String, ? extends Session> sessionIdToSession = sessionRepository
//                        .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, i.toString());
//                // 移除用户的 session 信息
//                List<String> sessionIds = new ArrayList<>(sessionIdToSession.keySet());
//                for (String session : sessionIds) {
//                    redisOperationsSessionRepository.deleteById(session);
//                }
//                lineTimeService.countLineTime("3", i.toString(), Instant.now() + "");
//            } catch (Exception e) {
//                errorId.add(i.toString());
//            }
//        });
//        JSONObject json = new JSONObject();
//        json.put("set", set);
//        json.put("size", set.size());
//        json.put("errorId", errorId);
//        return json;
//    }

    @GetMapping(value = "/testNetEase/eventType3")
    public Object lineTimeEventType3(HttpServletRequest request, String sex) {
//        List<Long> userIds = CommonUtil.changeIds(ids);
//        userIds.forEach(i->{
//            lineTimeService.countLineTime("3",i+"", Instant.now()+"");
//        });
        Set<Object> userIds = lineTimeRedisDao.getLineHashKeys();
        if (userIds == null || userIds.size() == 0) {
            return 0;
        }
        userIds.forEach(userId -> {
            User user = userInfoDao.getUserInfoById(Long.parseLong(userId+""));
            lineTimeService.countLineTime("3", userId+"", Instant.now().toEpochMilli() + "",user);
        });
        return userIds;
    }

    @GetMapping(value = "/testNetEase/senderBlackList/{phone}")
    public void addSmsSenderBlacklist(@PathVariable("phone") String phone) {
        smsSenderRedisDao.addSmsSenderBlacklist(phone);
    }

    @GetMapping(value = "/testNetEase/userVipLevel")
    public void userVipLevel(HttpServletRequest request) {
        List<UserVip> userVipList = userVipDao.getUserVipListByVipLevel();
        userVipList.forEach(i -> {
            userInfoDao.updateUserVipLevel(i.getUserId(), i.getVipLevel());
        });
    }

    @GetMapping(value = "/testNetEase/getOpenApiStatus")
    public OpenApiStatus getOpenApiStatus(HttpServletRequest request) {
        CommonHead com = VerifyUtil.verifyCommonHead(request);
        String appPackageId = com.getAppPackageId();
        String channelId = com.getChannel();
        String phoneSystem = com.getPhoneSystem();
        String versionNum = com.getVersionNum();
        OpenApiStatus openApiStatus = openApiStatusDao.getOpenApiStatus(versionNum, Integer.parseInt(phoneSystem)
                , appPackageId, channelId);
        return openApiStatus;
    }

//    @GetMapping(value = "/testNetEase/ip/{ip}")
//    public Object getOpenApiStatus(@PathVariable("ip") String ip){
//        String str = QueryIpRegion.queryIP(ip);
//        System.out.println(str);
//        JSONObject jsStr = JSONObject.parseObject(str);
//        String ret = jsStr.get("ret").toString();
//        String data = jsStr.get("data").toString();
//        net.sf.json.JSONArray json = net.sf.json.JSONArray.fromObject(data);
////        System.out.println(str);
////        String[] strings = str.split("\t");
////        String[] strings1 = strings[1].split(" ");
////        return strings1;
//
//        return json.get(0);
//    }

    /**
     * 云信-云顿测试
     * @param text 要测试的文本内容
     * @return 测试结果
     */
    @GetMapping(value = "/testNetEase/check")
    public Object getYunCheck(@RequestParam("text") String text) {
        String temp = "";
        try {
            temp = NetEaseCloudUserService.getYunTextCheck(text);
        } catch (Exception e) {
            temp = e.getMessage();
        }
        return temp;
    }

    @GetMapping(value = "/testNetEase/getIp")
    public String getIp(HttpServletRequest request) {
        String ip = ServletTool.getRemoteHost(request);
        return ip;
    }

    /**
     * 获取在线用户
     */
    @GetMapping(value = "/testNetEase/lineUserList")
    public JSONObject lineUserList() {
        //获取在线主播
        Set<String> hostLine = lineTimeRedisDao.getHostLine();
        Set<String> hostCall = userCallRedisDao.getHostCall();
        Set<String> boySet = lineTimeRedisDao.getHostLineBySex(1);
        Set<String> girlSet = lineTimeRedisDao.getHostLineBySex(2);
        JSONObject json = new JSONObject();
        json.put("在线主播：", hostLine);
        json.put("正在通话主播：", hostCall);
        json.put("在线男主播：", boySet);
        json.put("在线女主播：", girlSet);
        json.put("在线用户：", hostLine);
        return json;
    }

    @GetMapping(value = "/testNetEase/smsSender/{phone}")
    public void smsSender(HttpServletRequest request, @PathVariable("phone") String phone) {
        CommonHead com = VerifyUtil.verifyCommonHead(request);
        int verificationCode = (int) ((Math.random() * 9 + 1) * 1000); //生成验证码
        //注册验证码 349694
//        SmsSender smsSender = new SmsSender(phone,349694,verificationCode);
        //绑定验证码 349689
        SmsSender smsSender = new SmsSender(phone, 349689, verificationCode + "");
        smsSender.sendSms(com, getConfigSmsSing(com));
    }

    private String getConfigSmsSing(CommonHead com) {
        List<ConfigSms> configSmsList = configSmsDao.listConfigSms();
        String sign = "";
        String huamiSign = "";
        for (ConfigSms c : configSmsList) {
            if (c.getAppPackageId().equals("huami")) {
                huamiSign = c.getSignId();
            }
            if (c.getAppPackageId().equals(com.getAppPackageId())) {
                sign = c.getSignId();
            }
        }
        if (sign.equals(""))
            sign = huamiSign;
        return sign;
    }

    @GetMapping(value = "/testNetEase/HostUserCoverUrl")
    public int giftSpendMessage() {
        List<User> userList = userInfoDao.getHostList();
        int result = 0;
        for (User user : userList) {
            if (user.getUserCoverUrl() != null && !user.getUserCoverUrl().equals("")) {
                UserCoverUrl temp = new UserCoverUrl();
                temp.setUserId(user.getUserId());
                temp.setCoverUrl(user.getUserCoverUrl());
                temp.setState(1);
                temp.setId(idCreater.newCoverUrlIdByUserId(user.getUserId()));
                int num = userCoverUrlDao.insertUserCoverUrl(temp);
                result += num;
            }
        }
        return result;
    }


    /**
     * 黑白包3：探聊 情约功能数据处理
     */
    @GetMapping(value = "/testNetEase/getQinMiJSON")
    public List<String> getQinMiJSON() {
        //获取在线主播
        long[] boyStr = {15997400, 15997300, 15997100, 15985300, 15984900, 15986900, 15986700, 15986400,
                15986200, 15986100, 15987900, 15988000, 15988400, 15988700, 15983000, 15984800, 15981900,
                15981200, 15980800, 15980700, 15980200, 15979900};
        long[] girlStr = {11167400, 11167500, 11167600, 11167900, 11168300, 11168600, 11169100, 11169700,
                11170200, 11170800, 11171200, 11171400, 11171500, 11171600, 11171700, 11171800, 11171900,
                11172000, 11172100, 11172300, 11172400, 11172700};
        List<Long> boyIdList = Longs.asList(boyStr);
        List<Long> girlIdList = Longs.asList(girlStr);
        List<User> boyList = userInfoDao.getUserListByUserIds(boyIdList);
        List<User> girlList = userInfoDao.getUserListByUserIds(girlIdList);
        List<String> returnList = new ArrayList<>();
        JSONObject json = new JSONObject();
        Random rand = new Random();
        for (int i = 0; i < boyList.size(); i++) {
            int randNum = rand.nextInt(299) + 1;
            json.put("num", randNum);
            json.put("boyUserId", boyList.get(i).getUserId());
            json.put("boyNickName", boyList.get(i).getNickName());
            json.put("boyIcon", boyList.get(i).getIcon());
            json.put("girlUserId", girlList.get(i).getUserId());
            json.put("girlNickName", girlList.get(i).getNickName());
            json.put("girlIcon", girlList.get(i).getIcon());
            returnList.add(json.toJSONString());
        }
        return returnList;
    }

    @GetMapping(value = "/testOnline")
    public List<User> getOnLineUser() {
        long[] onLineUsers = {15953500, 15953400, 15953200, 15953000, 15952200, 15951700, 15951400, 15951200, 15951100
                , 16025300, 16024700, 16023900, 16024200, 16023500, 16021400, 16020100, 57838600, 57834800, 57833900, 57832400
                , 57832000, 57820000, 56897300, 56746900, 56762200};
        List<Long> onLineUser = Longs.asList(onLineUsers);
        List<User> qualityOnLineByUserIds = userInfoDao.getQualityHostByUserIds(onLineUser);
        List<User> lineUserList = new ArrayList<>();
        List<User> tempList = new ArrayList<>();
        lineUserList = qualityOnLineByUserIds.stream()
                .filter(i -> i.getIsLine() == 1)
                .sorted(comparing(User::getmGradeSum).reversed())
                .collect(toList());
        tempList = qualityOnLineByUserIds.stream()
                .filter(i -> i.getIsLine() != 1)
                .sorted(comparing(User::getmGradeSum).reversed()).collect(toList());
        lineUserList.addAll(tempList);
        return lineUserList;
    }


    @PostMapping(value = "/testNetEase/match")
    public Map<Long, String> getMatch(Long userId, String city) {
        return matchHostService.getMatchHostIds(userId, city);
    }

    @PostMapping(value = "/testNetEase/match/send")
    public void getMatch(Long userId, String ids, String city) {
        List<Long> list = CommonUtil.changeIds(ids);
        Map<Long, String> map = new HashMap<>();
        for (Long i : list) {
            map.put(i, null);
        }
        matchHostService.sendMsg(userId, map, city);
    }

    @GetMapping(value = "/testNetEase/qualityHostList")
    public List<User> testQualityHostList(HttpServletRequest request, String ids) {
        List<Long> list = CommonUtil.changeIds(ids);
        List<User> userList = userInfoDao.getQualityHostByUserIds(list);
        userList.forEach(i -> {
            // 生日转换成年龄
            if (i.getBirthday() != null) {
                i.setAge(SumAgeUtil.getAgeByBirth(i.getBirthday()));
                i.setBirthdayInstant(i.getBirthday().toString());
            }
            //主播状态设置 0离线，1在线，2繁忙，3勿扰
            i.setIsLine(0);
        });
        return userList;
    }

    @ApiOperation(value = "测试get", notes = "2")
    @GetMapping(value = "/testNetEase/hahaha")
    public List<UserVideo> t(HttpServletRequest request, String ids) {
        List<Long> videoIds = CommonUtil.changeIds(ids);
        List<UserVideo> list = homeVideoDao.listVideoWithUser(videoIds);
        for (UserVideo video : list) {
            video.setLineStatus(UserLineStatusConstant.ON_LINE);
            video.setUserLike(false);
            video.setUserFollow(false);

            //转换
            video.setDescribe(CommonUtil.null2String(video.getDescribe()));
            video.setLove(CommonUtil.null2Int(video.getLove()));
            video.setCommentNum(CommonUtil.null2Int(video.getCommentNum()));
            video.setCity(CommonUtil.null2String(video.getCity()));
            video.setNickName(CommonUtil.null2String(video.getNickName()));
            video.setVideoPrice(CommonUtil.null2String(video.getVideoPrice()));
            video.setIcon(CommonUtil.null2String(video.getIcon()));
            video.setVidType(CommonUtil.null2Int(video.getVidType()));
            video.setState(CommonUtil.null2Int(video.getState()));
        }

        //按videoIds排序
        List<UserVideo> result = new ArrayList<>();
        for (Long id : videoIds) {
            for (UserVideo userVideo : list) {
                if (userVideo.getVideoId().equals(id)) {
                    result.add(userVideo);
                }
            }
        }
        return result;
    }

    @GetMapping(value = "/testNetEase/{userId}/{hostUserId}")
    public JSONObject test(@PathVariable("userId") int userId, @PathVariable("hostUserId") int hostUserId) {
        JSONObject body = new JSONObject();
        JSONObject json = new JSONObject();
        JSONObject ext = new JSONObject();
        ext.put("type", 4);
        json.put("userId", userId);
        body.put("msg",
                "https://miliao-test.oss-cn-hangzhou.aliyuncs.com/miliao/video/d14d3b65b9ab4c71a0971f266e2a5e1d.mp4");
        json.put("body", body.toString());
        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, hostUserId, 100, body.toString(), ext.toString(), "");
            json.put("returnMsg", temp);
        } catch (Exception e) {
            json.put("returnMsg", e.toString());
        }
        return json;
    }

    @GetMapping(value = "/testNetEase/txt/{userId}/{hostUserId}")
    public JSONObject txt(@PathVariable("userId") int userId, @PathVariable("hostUserId") int hostUserId) {
        JSONObject body = new JSONObject();
        JSONObject json = new JSONObject();
        json.put("userId", userId);
        body.put("msg", "测试文字！！~~~！！！~~~");
        json.put("body", body.toString());
        JSONObject ext = new JSONObject();
        ext.put("type", 1);
        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, hostUserId, 0, body.toString(), ext.toString(), "");
            json.put("returnMsg", temp);
        } catch (Exception e) {
            json.put("returnMsg", e.toString());
        }
        return json;
    }

    @GetMapping(value = "/testNetEase/pic/{userId}/{hostUserId}")
    public JSONObject pictureMessage(@PathVariable("userId") int userId, @PathVariable("hostUserId") int hostUserId) {
        JSONObject json = new JSONObject();
        JSONObject body = new JSONObject();
        body.put("name", System.currentTimeMillis());// 图片name
        try {
            String content = "http://resources.goliaoyou.com/miliao/photos/6c84898991eb46239329fcda0fa3ee68.jpg";
            URL url = new URL(content);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedImage sourceImg = ImageIO.read(in);
            int w = sourceImg.getWidth();
            int h = sourceImg.getHeight();
            body.put("md5", DigestUtils.md5Hex(in));// 图片文件md5
            body.put("url", content);
            String[] temp = content.split("\\.");
            body.put("ext", temp[temp.length - 1]);
            body.put("w", w);
            body.put("h", h);
            // 根据响应获取文件大小
            body.put("size", conn.getContentLength());
        } catch (Exception e) {
            json.put("returnMsg", e.toString());
        }
        //开发者扩展字段
        JSONObject ext = new JSONObject();
        ext.put("imagetype", 1);
        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, hostUserId, EnumType.PICTURE_MESSAGE.state, body.toString(), ext.toString(), "");
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                json.put("returnMsg", temp);
        } catch (Exception e) {
            json.put("returnMsg", e.toString());
        }
        return json;
    }

    @GetMapping(value = "/testNetEase/testMQProducer")
    public void testMQProducer(String str) {
        rabbitTemplate.convertAndSend("testExchange", "testRoutingKey", str);
    }

    @GetMapping(value = "/testSendMessage/{userId}")
    public void testSendMessage(@PathVariable("userId") int userId) {
        String message = "恭喜您成功注册，踏上寻友之旅！我们诚邀您申请认证，认证后您能通过聊天互动、分享照片视频等多种玩法获得钻石奖励。所有钻石均可提现,体验交友赚钱的快感！";
        // String message = "http://pah5.peiwoliao.cn/IOS_TEST/index.html?key=1557467053136275733&appPackageId=huami&channel=test&phoneSystem=1&versionNum=1.0&userId=10091600";
        JSONObject body = new JSONObject();
        body.put("msg", message);
        //开发者扩展字段
        JSONObject ext = new JSONObject();
        ext.put("buttonType", EnumType.BUTTON_TYPE.state);

        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, EnumType.HELPER_USER_ID.state,
                    EnumType.TEXT_MESSAGE.state, body.toString(), ext.toString(), "");
            log.info("手机注册成功女用户发送消息 userId={},body={},ext{}", userId, body.toString(), ext);
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")) {
                log.error("发送点对点普通消息异常-云信：userId={},message={}", userId, temp);
            }

        } catch (Exception e) {
            log.error("发送点对点普通消息异常：userId={},error={}", userId, e);
        }
//        vestRobotMessageService.getSendMsgByIosToH5(userId,message);
    }


    @GetMapping("/testSendRegisterMessage/{userId}")
    public void sendRegisterMessage(@PathVariable("userId") long userId) throws UnsupportedEncodingException {
//        try {
//            String message = "温馨提示：\n" +
//                    "本平台是绿色健康交友平台，供成年人交友使用，未成年人乖乖在家学习，不准使用哦\n";
//            Map<String,String> map=new HashMap<String,String>();
//            map.put("title", "寻寻");
//            map.put("type", "1");
//            map.put("message", message);
//            ObjectMapper mapper = new ObjectMapper();
//            String createLogInfo= NetEaseCloudUserService.getSystemMessage(mapper.writeValueAsString(map), userId);
//            log.info("sendRegisterMessage系统消息发送成功：message={},userid={}",map.get("message"),userId);
//            if(!createLogInfo.substring(createLogInfo.indexOf("code")+6, createLogInfo.indexOf("code")+9).equals("200")){
//                if(log.isErrorEnabled()){
//                    log.error("sendRegisterMessage系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
//                }
//            }
//        } catch (Exception e) {
//            log.error("sendRegisterMessage系统消息发送IM错误：参数-" + userId,e);

//        }
        sendPayInfoByIos("test","1.5.4","xunxun-yonghu","2",userId);
    }

    private void sendPayInfoByIos(String channelId, String versionNum, String appPackageId,
                                  String phoneSystem, long userId) throws UnsupportedEncodingException {
        String h5PayUrl = appKeyService.getAppKeyByKey("iosH5PayUrl").getValue();
        if (StringUtils.isEmpty(channelId)) {
            channelId = "default";
        }
        if (StringUtils.isEmpty(versionNum)) {
            versionNum = "default";
        }
        String parameter = "appPackageId=" + URLEncoder.encode(appPackageId, "UTF-8") +
                "&channel=" + URLEncoder.encode(channelId, "UTF-8") + "&phoneSystem=" + phoneSystem +
                "&versionNum=" + URLEncoder.encode(versionNum, "UTF-8") +
                "&userId=" + userId;
        String url = h5PayUrl + "?" + parameter;

        Map<String, Object> ext = new HashMap<>(1);

        ext.put("redirectUrl", url);

        String template = SpendSystemMessage.IOS_PREFERENTIAL_RECHARGE.getMessage();
        ext.put("template", template);

        List<String> templateValueList = new ArrayList<>(1);
        templateValueList.add(url);

        ext.put("templateValue", templateValueList);

        String message = SpendSystemMessage.IOS_PREFERENTIAL_RECHARGE.getMessage(url);

        vestRobotMessageService.getSendMsg(userId, message,
                SpendSystemMessageType.IOS_PREFERENTIAL_RECHARGE_TYPE.getCode(), ext);
    }

    @GetMapping("/testTakllSkillMessage/{outId}-{insertId}/{num}")
    public void sendTakllingSkillMessage(@PathVariable("outId") long outId, @PathVariable("insertId") long insertId, @PathVariable("num") int num) {
        talkingSkillService.sendTalking(outId, insertId, num);

    }

    @GetMapping("/testUserLoginMessage/{outId}")
    public void sendTakllingSkillMessage(@PathVariable("outId") long outId) {
//        if (!stringRedisTemplate.opsForSet().isMember(EnumRedisKey.SET_USER_LOGIN_EVERYDAY.getValue(), outId + "")) {
//            stringRedisTemplate.opsForSet().add(EnumRedisKey.SET_USER_LOGIN_EVERYDAY.getValue(), outId + "");
        MessageSystemUtil.sendCustomSystemMessage(outId, EVERYDAY_MESSAGE);
//        }
    }


    @GetMapping("/testUserLevel/init")
    public void testUserLevelInit() {
        List<User> list = userInfoDao.getHostUserInfoList();
        for (User obj : list) {
            int integral = obj.getmGradeSum() / 100;
            userCountDao.updateIntegralSum(obj.getUserId(), integral);
        }

    }

    @GetMapping("/testFans/init")
    public void testFansInit() {
        List<Long> list = userInfoDao.getTestUserList();

        long hostUserId = 10004200;
        for (Long userId : list) {
            Follow entity = new Follow(userId, hostUserId);
            followRedisDao.insertFollow(entity);
        }

    }

    @GetMapping("/testComment/init")
    public void getTestCommentInit() {
        List<Long> list = userInfoDao.getTestUserList();
        int i = 1;
        for (Long userId : list) {
            if (i <= 23) {
                integralRewardsAndPunishmentsHandler
                        .singleDynamicCommentAndReplyOver10People(331,
                                10089901, userId);
            }
            i++;

        }
    }

    @GetMapping("/activityRewards")
    public void activityRewards(String key) {
        String sign = "1qaz2wsx";
        if (sign.equals(key)) {
            if (LocalDate.now().equals(LocalDate.of(2019, 8, 30))) {
                coolSummerActivitiesService.activityRewards();
                sanGuoGameActivityService.giveUserSendBeans();
            }
        }
    }

    @GetMapping("/testGameRangking/list")
    public void sendGameRangkingList() {
        List<GameAllRankingListDTO> gameAllRankingDayList = gameAllRankingListDao.selectGameListByDay(LocalDate.now().minusDays(1));
        for (int i = 0; i < gameAllRankingDayList.size(); i++) {
            if (gameAllRankingDayList.get(i).getIsRobot() != 1) {
                int flag = userWalletDao.updateBeans(gameAllRankingDayList.get(i).getUserId(), GameRankingListUtil.getGuoRewardMapByDay().get(i));
                if (flag > 0) {
                    GameAllRankingListLogDTO gameAllRankingListLog = new GameAllRankingListLogDTO();
                    gameAllRankingListLog.setUserId(gameAllRankingDayList.get(i).getUserId());
                    gameAllRankingListLog.setProfit(gameAllRankingDayList.get(i).getReturnBean());
                    gameAllRankingListLog.setSort((i + 1) + "");
                    gameAllRankingListLog.setRewardsBeans(GameRankingListUtil.getGameRankingRewardListByDay().get(i));
                    gameAllRankingListLog.setRewardsType(1);
//                    gameAllRankingListLog.setCreatTime(LocalDateTime.now());
//                    gameAllRankingListLog.setCreatDate(LocalDate.now());
                    gameAllRankingListLog.setRankingDate(gameAllRankingDayList.get(i).getCreateDate());
                    int j = gameAllRankingListLogDao.saveGameAllRankingListLog(gameAllRankingListLog);
                    if (j > 0) {
                        BillDetailBeans billDetailBeans = new BillDetailBeans();
                        billDetailBeans.setBeansType(BeansType.GAME_PROFIT_DAY_REWARDS__GIVE_BEANS.getCode());
                        billDetailBeans.setBeans(GameRankingListUtil.getGuoRewardMapByDay().get(i));
                        billDetailBeans.setRatio(0);
                        billDetailBeans.setUserId(gameAllRankingDayList.get(i).getUserId());
                        billDetailBeansDao.insertBillDetailBeans(billDetailBeans);

                        //发送系统消息 TODO 消息可优化 可放在common项目的枚举中
                        String message = "恭喜您，昨天盈利排行榜排名第" + (i + 1) + "名，继续加油哦！";
                        MessageSystemUtil.sendCustomSystemMessage(gameAllRankingDayList.get(i).getUserId(), message);
                    }
                }
            }
        }

        //获取通话时长日排行榜发送系统消息
        String callTimeKey = CallTimeRankingListKey.getDayRankingListKey(LocalDate.now().minusDays(1));
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeWithScores(callTimeKey, 0, 49);
        Iterator<ZSetOperations.TypedTuple<String>> iterator = typedTuples.iterator();
        //便历排行榜 获得主播userId 发放系统消息
        while (iterator.hasNext()) {
            ZSetOperations.TypedTuple<String> typedTuple = iterator.next();
            String userId = typedTuple.getValue();
            Long reverseRank = stringRedisTemplate.opsForZSet().reverseRank(callTimeKey, Long.parseLong(userId));
            String callTimeMessage = "恭喜您，昨天通话榜排名第" + reverseRank + "名，继续加油哦！";
            MessageSystemUtil.sendCustomSystemMessage(Long.parseLong(userId), callTimeMessage);
        }

        //获取钻石日排行榜发送系统消息
        String diamondKey = DiamondRankingListKey.getDayRankingListKey(LocalDate.now().minusDays(1));
        Set<ZSetOperations.TypedTuple<String>> typedTuples1 = stringRedisTemplate.opsForZSet().reverseRangeWithScores(diamondKey, 0, 49);
        Iterator<ZSetOperations.TypedTuple<String>> iterator1 = typedTuples.iterator();
        //便历排行榜 获得主播userId 发放系统消息
        while (iterator1.hasNext()) {
            ZSetOperations.TypedTuple<String> typedTuple = iterator.next();
            String userId = typedTuple.getValue();
            Long reverseRank = stringRedisTemplate.opsForZSet().reverseRank(diamondKey, Long.parseLong(userId));
            String callTimeMessage = "恭喜您，昨天钻石榜排名第" + reverseRank + "名，继续加油哦！";
            MessageSystemUtil.sendCustomSystemMessage(Long.parseLong(userId), callTimeMessage);
        }
    }

    @GetMapping("/initHostRecentDevelopments")
    public void initHostRecentDevelopments() throws IOException {

        List<User> userList = userInfoDao.getHostList();


        for(User user : userList){

            boolean bl = hostRecentDevelopmentsRedisDao.existKey(user.getUserId());

            if(!bl){
                List<HostRecentDevelopmentsDTO> resultList = new ArrayList<>();
                List<FindDynamicVO> dynamicList = findDynamicElasticsearch
                        .selectIndividualPage(10000, user.getUserId(), 1, 3, "123");
//                        .getFindDynamicIdsPageByUserId(user.getUserId(),0,3);

                for(FindDynamicVO vo : dynamicList){
                    HostRecentDevelopmentsDTO obj = new HostRecentDevelopmentsDTO();
                    obj.setType(1);
                    obj.setUserId(user.getUserId());
                    obj.setFindId(vo.getFindId());
                    resultList.add(obj);
                }

                if(resultList.size()<3){
                    int pageSize = 3 - resultList.size();
                    List<UserVideo> userVides = userVideoDao
                            .listUserVideoPageFree(user.getUserId(), 0, pageSize);

                    for(UserVideo obj : userVides){
                        HostRecentDevelopmentsDTO dto = new HostRecentDevelopmentsDTO();
                        dto.setType(3);
                        dto.setUserId(user.getUserId());
                        dto.setVideoImageUrl(obj.getCoverUrl());
                        dto.setVideoUrl(obj.getVidUrl());
                        resultList.add(dto);
                    }

                }

                if(resultList.size()<3){
                    int pageSize = 3- resultList.size();
                    List<String> picList =privatePhotoDao
                            .getPrivatePhotoFreeByuserId(user.getUserId(),0,pageSize);
                    for(String url : picList){
                        HostRecentDevelopmentsDTO dto = new HostRecentDevelopmentsDTO();
                        dto.setType(2);
                        dto.setUserId(user.getUserId());
                        dto.setPhotoUrl(url);
                        resultList.add(dto);
                    }
                }
                hostRecentDevelopmentsMQ.setHostRecentDevelopmentsMessage(resultList);
            }
        }


    }

    @GetMapping("/deleteHostRecentDevelopments")
    public void deleteHostRecentDevelopments(){
        List<User> userList = userInfoDao.getHostList();
        for(User user : userList){
            hostRecentDevelopmentsRedisDao.delete(user.getUserId());

        }
    }
}
